package com.time.workshop.ui;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.time.workshop.API;
import com.time.workshop.App;
import com.time.workshop.BaseConstant;
import com.time.workshop.R;
import com.time.workshop.SuperActivity;
import com.time.workshop.adapter.AbsViewHolderAdapter;
import com.time.workshop.adapter.DingZuoAdapter;
import com.time.workshop.bean.CountyList;
import com.time.workshop.bean.ShopList;
import com.time.workshop.bean.WaimaiType;
import com.time.workshop.injector.Injector;
import com.time.workshop.injector.V;
import com.time.workshop.utils.CommonUtils;
import com.time.workshop.utils.IDropdownItemClickListener;
import com.time.workshop.utils.LaoBanDialog;
import com.time.workshop.utils.NewToast;
import com.time.workshop.utils.ScreenSizeUtil;
import com.time.workshop.utils.TitlePopupwindow;

/**
 *   外卖列表
 * 
 * @author fanbaolong
 *
 */
public class WaiMaiActivity extends SuperActivity {

	private WaiMaiAdapter mAdapter;
	@V
	private ListView waimai_list;
	@V
	private Button waimai_titlebar_left_btn;
	@V
	private TextView address_selete_but;
	@V
	private RelativeLayout waimai_titlebar_content,empty_relat;

	private  LaoBanDialog dlg;

	private  List<WaimaiType> waimaiTypes;

	List<String> mList = new ArrayList<String>();
	private List<CountyList> countyList = new ArrayList<CountyList>();
	private String county_id;
	@Override
	protected void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		setContentView(R.layout.activity_waimai);
		App.street_id = "";
		App.street_name = "";
		App.county_id = "";
		App.county_name = "";

		waimaiTypes = new ArrayList<WaimaiType>();
		reqCounty();
		reqStoreList();
		init();

		setItemClickListen();
	}
	private void reqCounty() {
		if (!CommonUtils.isNetworkConnected(getApplicationContext())) {
			NewToast.makeText(getApplicationContext(), getResources().getString(R.string.M000));
			return;
		}
		showDialog(null);
		App.cityId = "SZ";
		RequestParams params = new RequestParams();
		params.addQueryStringParameter("pid", App.cityId);

		HttpUtils httpUtils = new HttpUtils();

		httpUtils.send(HttpMethod.GET, API.areaList,params,new RequestCallBack<String>() {

			@Override 
			public void onSuccess(ResponseInfo<String> responseInfo) {
				Log.d("onSuccess==", responseInfo.result+"");

				dismissLoadingDialog();
				if (responseInfo.result.length() != 0) {


					try {
						JSONArray jsonObject = new JSONArray(responseInfo.result);

						Gson gson = new Gson();
						System.out.println("jsonObject.toString()::"+jsonObject.toString());

						countyList = gson.fromJson(jsonObject.toString(), new TypeToken<List<CountyList>>() {
						}.getType());

						if (countyList.size() != 0) {
							address_selete_but.setText(countyList.get(0).getNAME());
							county_id = countyList.get(0).getID();
						}

					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}

			@Override
			public void onFailure(HttpException error, String msg) {
				dismissLoadingDialog();
				Log.d("onFailure==", msg+"");
				NewToast.makeText(getApplicationContext(), R.string.get_country_failure);
			}
		});
	}
	private void reqStoreList() {
		//		province_id:省份ID
		//		city_id:市ID
		//		county_id:区县ID
		//		street_id:街道ID
		//		type:店铺类型(0订座,1外卖,2挂号)
		//		out_type:外卖类型ID
		int type = 0;
		if (BaseConstant.WAIMAI == App.getInstance().type) {
			type = 1;
		}else {
			return;
		}

		showDialog(null);
		RequestParams params = new RequestParams();
		params.addQueryStringParameter("province_id", "");
		params.addQueryStringParameter("city_id", App.cityId);
		params.addQueryStringParameter("county_id", county_id);
		params.addQueryStringParameter("street_id", App.street_id);
		params.addQueryStringParameter("type", type+"");
		params.addQueryStringParameter("out_type", "");

		HttpUtils httpUtils = new HttpUtils();

		httpUtils.send(HttpMethod.GET, API.shopList,params,new RequestCallBack<String>() {

			@Override 
			public void onSuccess(ResponseInfo<String> responseInfo) {
				Log.d("shopList——onSuccess==", responseInfo.result+"");

				dismissLoadingDialog();
				if (responseInfo.result.length() != 0) {
					try {
						JSONArray jsonObject = new JSONArray(responseInfo.result);

						Gson gson = new Gson();
						System.out.println("jsonObject.toString()::"+jsonObject.toString());

						waimaiTypes = gson.fromJson(jsonObject.toString(), new TypeToken<List<WaimaiType>>() {
						}.getType());

						if (waimaiTypes.size() == 0) {
							empty_relat.setVisibility(View.VISIBLE);
							waimai_list.setVisibility(View.GONE);
							NewToast.makeText(getApplicationContext(), "暂时没有数据");
						}else {
							empty_relat.setVisibility(View.GONE);
							waimai_list.setVisibility(View.VISIBLE);
						}
						
						System.out.println("waimaiTypes:"+waimaiTypes.toString());
						WaiMaiAdapter madapter = new WaiMaiAdapter(WaiMaiActivity.this,waimaiTypes,R.layout.item_waimai_list);
						waimai_list.setAdapter(madapter);

						//madapter.notifyDataSetChanged();

					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}

			@Override
			public void onFailure(HttpException error, String msg) {
				dismissLoadingDialog();
				Log.d("onFailure==", msg+"");
				NewToast.makeText(getApplicationContext(), R.string.login_failure);
			}
		});
	}


	private void setItemClickListen() {

		waimai_list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position,
					long id) {

				Intent intent = new Intent(WaiMaiActivity.this,WaiMaiOrderActivity.class);
				WaimaiType waimai = waimaiTypes.get(position);
				intent.putExtra("waimai", waimai);
				startActivity(intent);

			}
		});

	}
	@Override
	public void onResume() {
		super.onResume();
		if (!CommonUtils.isNull_nie(App.street_id)) {
			address_selete_but.setText(App.street_name);
			county_id = App.county_id;
			reqStoreList();
		}else if (!CommonUtils.isNull_nie(App.county_id)) {
			address_selete_but.setText(App.county_name);
			county_id = App.county_id;
			reqStoreList();
		}
	
	}

	private void init() {
		Injector.getInstance().inject(this);

		waimai_titlebar_left_btn.setOnClickListener(this);
		address_selete_but.setOnClickListener(this);

		//		mAdapter = new WaiMaiAdapter(this, R.layout.item_waimai_list);
		//		waimai_list.setAdapter(mAdapter);
		//
		//		mAdapter.update(mList);

	}

	public void onClick(View v){
		switch (v.getId()) {
		case R.id.waimai_titlebar_left_btn:
			back();

			break;
		case R.id.address_selete_but:
			//showPopup(v);
			if (countyList.size() != 0) {
				//	showPopup(v);
				Intent intent = new Intent(this,AddressCountyActivity.class);
				intent.putExtra("countyList", (Serializable)countyList);
				startActivity(intent);
			}
			break;

		default:
			break;
		}
	}
	/**显示地区弹出框 */
	private void showPopup(View v){
		List<String> list = new ArrayList<String>();
		list.add("吴中区");
		list.add("工业园区");
		list.add("高新区");
		int[] location = new int[2];
		v.getLocationInWindow(location);
		location[1] = location[1] + waimai_titlebar_content.getHeight();
		TitlePopupwindow title = new TitlePopupwindow(WaiMaiActivity.this, list);
		ScreenSizeUtil util = new ScreenSizeUtil(WaiMaiActivity.this);
		int width = util.getScreenWidth();
		int height = util.getScreenHeight();
		title.showAt(location, width, height);
		title.setItemClickListener(new IDropdownItemClickListener() {

			@Override
			public void onItemClick(String text, int drawableId) {
				address_selete_but.setText(text);
			}
		});
	}



	public class WaiMaiAdapter extends AbsViewHolderAdapter<WaimaiType>{

		public WaiMaiAdapter(Context context,List<WaimaiType> list, int layoutRes) {
			super(context , list , layoutRes);
		}

		@Override
		protected void bindData(int pos, WaimaiType waimaiType) {
			TextView name = getViewFromHolder(R.id.item_waimai_shopname_text);
			TextView distance = getViewFromHolder(R.id.item_waimai_distance_text);
			TextView address = getViewFromHolder(R.id.item_waimai_address_text);
			ImageView img = getViewFromHolder(R.id.item_waimai_image);
			name.setText(waimaiType.getNAME());
			distance.setText(waimaiType.getDistance());
			address.setText(waimaiType.getADDRESS());
			ImageLoader.getInstance().displayImage(waimaiType.getPIC_URL(), img, getDisplayOption());
		}

	}

	private void dismisMyDialog() {

		if(  dlg != null && dlg.isShowing() ){
			dlg.dismiss();
		}
		dlg = null;

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		dismisMyDialog();
	}


}
